import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [todos, setTodos] = useState([
    {
      id: 1,
      todoName: '123',
      isDone: true,
    },
  ])

  useEffect(() => {
    const addId = PubSub.subscribe('add', (topic, todoName) => {
      // console.log(todoName)

      // setTodos(newTodos)

      setTodos((todos) => {
        // 这个todos一定是正确的数据
        const todo = {
          // 要求id的值是整数,并且不能重复
          //实现,如果数组中有数据,因为是往数组的后面添加数据,所以每次添加找到数组中最后一个数据,通过最后一个数据的id+1
          // 如果数组中没有数据,则第一条数据的id就写死是1
          id: todos.length ? todos[todos.length - 1].id + 1 : 1,
          todoName,
          isDone: false,
        }

        const newTodos = [...todos]

        newTodos.push(todo)
        return newTodos
      })
    })
    return () => {
      PubSub.unsubscribe(addId)
    }
  }, [])
  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {todos.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
